<?php

namespace app\screen\controller\work_area;

use app\admin\service\work_area\BusinessService;
use app\common\controller\Screen;
use app\common\model\haikang\HkConsumerMsg;
use app\common\model\haikang\HkConsumerMsgWeek;
use app\common\model\haikang\HkEventType;
use app\common\model\work_area\HkDeviceSerial;
use app\common\model\work_area\ProjLine;
use app\common\model\work_area\WarnVoice;
use app\common\model\work_area\WorkArea;
use app\common\model\work_area\WorkAreaStand;
use app\common\model\work_area\WorkAreaStandVoice;
use app\common\service\broadcast\IpBroadcastService;
use app\common\service\haikang\HaikangService;
use app\common\service\RedisQuantity;
use hg\apidoc\annotation as Apidoc;
use thans\jwt\facade\JWTAuth;
use think\db\Query;

/**
 * @Apidoc\Title("大屏数据展示")
 */
class Info extends Screen
{

    /**
     * @Apidoc\Title("项目列表")
     * @Apidoc\Url("/screen/work_area.Info/projLineList")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("id", type="int", desc="id"),
     *    @Apidoc\Returned("name", type="string", desc="名称"),
     *    @Apidoc\Returned("today", type="string", desc="当天"),
     *    @Apidoc\Returned("month", type="string", desc="当月"),
     *    @Apidoc\Returned("whole", type="string", desc="全部"),
     *    @Apidoc\Returned("workAreaList", type="array", desc="工区数组"),
     *    @Apidoc\Returned("work_area_stand", type="array", desc="站点数组"),
     * )
     */
    public function projLineList()
    {
        try {
            $list = ProjLine::field(['id', 'name', 'line_arr', 'line_style'])->with(['workAreaList' => function (Query $query) {
                $query->field('id,proj_line_id,name,is_use');
            }])
                ->cache(30)
                ->order('sort DESC')
                ->select()
                ->toArray();
            //只获取下面数组事件
            //$event_arr = BusinessService::$event_arr;
            foreach ($list ?? [] as $key => $val) {
                $list[$key]['today'] = 0;
                $list[$key]['month'] = 0;
                $list[$key]['whole'] = 0;
                $list[$key]['line_arr'] = $val['line_arr'] ?? [];
                //站点列表
                $work_area_stand = WorkAreaStand::where('work_area_id', 'IN', function ($query) use ($val) {
                    $query->name('work_area')->where(['proj_line_id' => $val['id']])->field('id');
                })
                    ->field(['id', 'name', 'longitude', 'latitude', 'is_use'])
                    ->select()
                    ->toArray();
                //工区列表
                $workAreaList = $val['workAreaList'];
                if (!empty($workAreaList)) {
                    $work_area_stand_id = array_column($work_area_stand, 'id');
                    //获取录像机设备编号
                    $list[$key]['today'] = HkConsumerMsgWeek::where(['work_area_stand_id' => $work_area_stand_id])->where('image_url', 'not null')->whereDay('date_time')->cache(30)->count('*');
                    $list[$key]['month'] = HkConsumerMsg::where(['work_area_stand_id' => $work_area_stand_id])->where('image_url', 'not null')->whereMonth('date_time')->cache(30)->count('*');
                    $list[$key]['whole'] = HkConsumerMsg::where(['work_area_stand_id' => $work_area_stand_id])->where('image_url', 'not null')->cache(30)->count('*');
                    unset($work_area_stand_id);
                    //工区列表数据
                    foreach ($workAreaList as $k => $v) {
                        //工区ID获取站点
                        $work_area_stand_id = WorkAreaStand::where('work_area_id', 'IN', function ($query) use ($v) {
                            $query->name('work_area')->where(['id' => $v['id']])->field('id');
                        })
                            ->field(['id', 'name', 'longitude', 'latitude', 'is_use'])
                            ->column('id');
                        $list[$key]['workAreaList'][$k]['today'] = HkConsumerMsgWeek::where(['work_area_stand_id' => $work_area_stand_id])->where('image_url', 'not null')->whereDay('date_time')->cache(30)->count('*');
                        $list[$key]['workAreaList'][$k]['month'] = HkConsumerMsg::where(['work_area_stand_id' => $work_area_stand_id])->where('image_url', 'not null')->whereMonth('date_time')->cache(30)->count('*');
                        $list[$key]['workAreaList'][$k]['whole'] = HkConsumerMsg::where(['work_area_stand_id' => $work_area_stand_id])->where('image_url', 'not null')->cache(30)->count('*');
                        unset($work_area_stand_id);
                    }
                }
                $list[$key]['work_area_stand'] = $work_area_stand;
                unset($work_area_stand);
                unset($workAreaList);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $list);
    }


    /**
     * @Apidoc\Title("站点统计")
     * @Apidoc\Url("/screen/work_area.Info/siteStatistics")
     * @Apidoc\Param("proj_line_id",type="int", desc="项目id 默认值传0")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("id", type="int", desc="id"),
     *    @Apidoc\Returned("name", type="string", desc="名称"),
     *    @Apidoc\Returned("today", type="string", desc="当天"),
     *    @Apidoc\Returned("month", type="string", desc="当月"),
     *    @Apidoc\Returned("whole", type="string", desc="全部"),
     *    @Apidoc\Returned("workAreaList", type="array", desc="工区数组"),
     * )
     */
    public function siteStatistics()
    {
        try {
            $proj_line_id = input('post.proj_line_id/d', 0);
            $work_area_id = input('post.work_area_id/d', 0);
            $where = [];
            //项目id
            if ($proj_line_id > 0) {
                $work_area_id_all = WorkArea::where(['proj_line_id' => $proj_line_id])->column('id');
                $where[] = ['work_area_id', 'in', $work_area_id_all];
            }
            //工区id
            if ($work_area_id > 0) {
                $where[] = ['work_area_id', '=', $work_area_id];
            }
            //只获取下面数组事件
            $event_arr_id = HkEventType::$event_arr_id;
            $hk_event_type = HkEventType::where(['id' => $event_arr_id])->column('remarks');
            //站点列表
            $list = WorkAreaStand::where($where)->order("sort DESC")->field(['id', 'name', 'addr', 'longitude', 'latitude', 'is_use'])->select()->toArray();
            foreach ($list as $key => $val) {
                foreach ($hk_event_type as $v) {
                    $list[$key]['statistics'][$v] = HkConsumerMsg::where(['work_area_stand_id' => $val['id'], 'msg_name' => $v])->cache(30)->count("*");
                }
                $list[$key]['today'] = HkConsumerMsgWeek::where('image_url', 'not null')->whereDay('date_time')->cache(30)->count('*');
                $list[$key]['month'] = HkConsumerMsg::where('image_url', 'not null')->whereMonth('date_time')->cache(30)->count('*');
                $list[$key]['whole'] = HkConsumerMsg::where('image_url', 'not null')->cache(30)->count('*');
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $list);
    }


    /**
     * @Apidoc\Title("工区列表")
     * @Apidoc\Url("/screen/work_area.Info/workAreaList")
     * @Apidoc\Param("proj_line_id",type="int", desc="项目id 默认值传0")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("id", type="int", desc="工区id"),
     *    @Apidoc\Returned("name", type="string", desc="工区名称"),
     *    @Apidoc\Returned("today", type="string", desc="当天"),
     *    @Apidoc\Returned("month", type="string", desc="当月"),
     *    @Apidoc\Returned("whole", type="string", desc="全部"),
     * )
     */
    public function workAreaList()
    {
        try {
            $where = [];
            $proj_line_id = input('post.proj_line_id/d', 0);
            $work_area_id = input('post.work_area_id/d', 0);
            //项目id
            if ($proj_line_id > 0) {
                $work_area_id_all = WorkArea::where(['proj_line_id' => $proj_line_id])->column('id');
                $where[] = ['id', 'in', $work_area_id_all];
            }
            //工区id
            if ($work_area_id > 0) {
                $where[] = ['id', '=', $work_area_id];
            }
            $list = WorkArea::where($where)
                ->order('sort DESC')
                ->field([
                    'id', 'name', 'addr', 'longitude', 'latitude'
                ])
                ->order("sort DESC")
                ->select()
                ->toArray();
            //只获取下面数组事件
            $event_arr = BusinessService::$event_arr;
            foreach ($list ?? [] as $k => $v) {
                //获取录像机设备编号
                $device_serial = BusinessService::areaDeviceList($v['id']);
                $list[$k]['today'] = HkConsumerMsgWeek::where(['msg_type' => $event_arr, 'device_serial' => $device_serial])->where('image_url', 'not null')->whereDay('date_time')->cache(30)->count('*');
                $list[$k]['month'] = HkConsumerMsg::where(['msg_type' => $event_arr, 'device_serial' => $device_serial])->where('image_url', 'not null')->whereMonth('date_time')->cache(30)->count('*');
                $list[$k]['whole'] = HkConsumerMsg::where(['msg_type' => $event_arr, 'device_serial' => $device_serial])->where('image_url', 'not null')->cache(30)->count('*');
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $list);
    }

    /**
     * @Apidoc\Title("大屏正中上方数据")
     * @Apidoc\Url("/screen/work_area.Info/cameraStats")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="工点id 默认值传0")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("camera_count", type="string", desc="摄像头总数"),
     *    @Apidoc\Returned("today_warn", type="string", desc="当天预警"),
     *    @Apidoc\Returned("all_warn", type="string", desc="累计预警"),
     * )
     */
    public function cameraStats()
    {
        try {
            $result = JWTAuth::auth();
            $user_type = $result['user_type'];
            $work_area_id = input('post.work_area_id/d', 0);
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            //摄像头总数
            $camera_count = 0;

            //条件
            $where = [];

            //默认获取全部的摄像头抓拍
            $device_serial = HkDeviceSerial::where('work_area_stand_id', 'IN', function ($query) {
                $query->name('work_area_stand')->where('delete_time', 0)->field('id');
            })
                ->cache(30)
                ->group('device_serial')->column('device_serial', 'id');
            $where[] = ['device_serial', 'in', $device_serial];

            //指挥部查看全部
            if ($user_type == 1 && $work_area_id == 0) {
                $camera_count = HkDeviceSerial::count('*');
            }
            //查看指定工区、或者站点
            if ($work_area_id > 0 || $work_area_stand_id > 0) {
                //获取全部摄像头
                if ($work_area_id > 0) $device_serial = BusinessService::areaDeviceList($work_area_id);
                if ($work_area_stand_id > 0) $device_serial = BusinessService::siteDeviceList($work_area_stand_id);
                $where[] = ['device_serial', 'in', $device_serial];
                $camera_count = HkDeviceSerial::where(['device_serial' => $device_serial])->cache(30)->count('*');
            }
            //当天预警
            $today_warn = HkConsumerMsgWeek::where($where)->whereDay('date_time')->cache(30)->count('*');
            //累计预警
            $all_warn = HkConsumerMsg::where($where)->where('image_url', 'not null')->cache(30)->count('*');
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', [
            'camera_count' => $camera_count,
            'today_warn' => $today_warn,
            'all_warn' => $all_warn
        ]);
    }


    /**
     * @Apidoc\Title("AI风险识别类型汇总分析")
     * @Apidoc\Url("/screen/work_area.Info/aiRiskType")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="站点id 默认值传0")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("open_safety_helmet_detection", type="string", desc="安全帽检测事件"),
     *    @Apidoc\Returned("ai_message_task_result", type="string", desc="反光衣"),
     *    @Apidoc\Returned("open_message_faildown", type="string", desc="人员倒地"),
     *    @Apidoc\Returned("open_message_smoke_and_fire", type="string", desc="烟火检测事件"),
     *    @Apidoc\Returned("open_play_cellphone", type="string", desc="玩手机检测事件")
     * )
     */
    public function aiRiskType()
    {
        try {
            $work_area_id = input('post.work_area_id/d', 0);
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            //只获取下面数组事件
            $event_arr_id = HkEventType::$event_arr_id;
            $hk_event_type = HkEventType::where(['id' => $event_arr_id])->column('remarks', 'id');

            $where = [];

            //默认获取全部的摄像头抓拍
            $device_serial = HkDeviceSerial::where('work_area_stand_id', 'IN', function ($query) {
                $query->name('work_area_stand')->where('delete_time', 0)->field('id');
            })
                ->cache(30)
                ->group('device_serial')->column('device_serial', 'id');
            $where[] = ['device_serial', 'in', $device_serial];

            //获取指定工区摄像头
            if ($work_area_id > 0) {
                $device_serial = BusinessService::areaDeviceList($work_area_id);
                $where[] = ['device_serial', 'in', $device_serial];
            }
            //获取指定站点摄像头
            if ($work_area_stand_id > 0) {
                $device_serial = BusinessService::siteDeviceList($work_area_stand_id);
                $where[] = ['device_serial', 'in', $device_serial];
            }
            $hk_consumer_msg = HkConsumerMsg::where($where)
                ->where(['msg_name' => $hk_event_type])
                ->where('image_url', 'not null')
                ->field(['msg_type', "count('msg_type') msg_type_count", 'msg_name remarks'])
                ->group('msg_name')
                ->cache(30)
                ->select()
                ->toArray();
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $hk_consumer_msg);
    }


    /**
     * @Apidoc\Title("当前视频设备在线率")
     * @Apidoc\Url("/screen/work_area.Info/deviceExist")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="站点id 默认值传0")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("on_line", type="int", desc="在线"),
     *    @Apidoc\Returned("offline", type="int", desc="离线"),
     *    @Apidoc\Returned("spear_on_line", type="int", desc="抢在线"),
     *    @Apidoc\Returned("ball_on_line", type="int", desc="球在线"),
     * )
     */
    public function deviceExist()
    {
        try {
            $work_area_id = input('post.work_area_id/d', 0);
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);

            $where = [];
            //获取工区摄像头
            if ($work_area_id > 0) {
                $device_serial = BusinessService::areaDeviceList($work_area_id);
                $where[] = ['device_serial', 'in', $device_serial];
            }
            //获取站点摄像头
            if ($work_area_stand_id > 0) {
                //获取全部摄像头
                $device_serial = BusinessService::siteDeviceList($work_area_stand_id);
                $where[] = ['device_serial', 'in', $device_serial];
            }
            //总数
            $total = HkDeviceSerial::where($where)->cache(30)->count('*');
            //在线
            $on_line = HkDeviceSerial::where($where)->where(['is_exist' => 1])->cache(30)->count('*');
            //离线
            $offline = HkDeviceSerial::where($where)->where(['is_exist' => 2])->cache(30)->count('*');
            //枪在线
            $spear_on_line = HkDeviceSerial::where($where)->where(['is_exist' => 1, 'type' => 1])->cache(30)->count('*');
            //球在线
            $ball_on_line = HkDeviceSerial::where($where)->where(['is_exist' => 1, 'type' => 2])->cache(30)->count('*');

            $data = [
                'on_line' => $on_line == 0 ? 0 : (int)floor(($on_line / $total) * 100),
                'offline' => $offline == 0 ? 0 : (int)floor(($offline / $total) * 100),
                'spear_on_line' => $spear_on_line == 0 ? 0 : (int)floor(($spear_on_line / $total) * 100),
                'ball_on_line' => $ball_on_line == 0 ? 0 : (int)floor(($ball_on_line / $total) * 100),
            ];
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $data);
    }

    /**
     * @Apidoc\Title("AI识别智能预警视频分析")
     * @Apidoc\Url("/screen/work_area.Info/aiImgList")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="站点id 默认值传0")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("event_name", type="string", desc="事件名"),
     *    @Apidoc\Returned("image_url", type="string", desc="海康图片地址"),
     *    @Apidoc\Returned("server_img_url", type="string", desc="服务器地址为null取image_url"),
     *    @Apidoc\Returned("date_time", type="int", desc="时间"),
     *    @Apidoc\Returned("name", type="string", desc="站点"),
     *    @Apidoc\Returned("dname", type="string", desc="工区名"),
     *    @Apidoc\Returned("broadcast", type="int", desc="语音 1播报 0不播报"),
     *    @Apidoc\Returned("is_camera", type="int", desc="摄像头 1爆红 0不报"),
     *    @Apidoc\Returned("voice_file", type="int", desc="播报地址")
     * )
     */
    public function aiImgList()
    {
        try {
            $result = JWTAuth::auth();
            $user_type = $result['user_type'];
            $work_area_user_id = $result['work_area_user'];
            $work_area_id = input('post.work_area_id/d', 0);
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            $where = [];
            //默认获取全部的摄像头抓拍
            $device_serial = HkDeviceSerial::where('work_area_stand_id', 'IN', function ($query) {
                $query->name('work_area_stand')->where('delete_time', 0)->field('id');
            })
                ->cache(30)
                ->column('device_serial', 'id');
            $where[] = ['a.device_serial', 'in', $device_serial];

            //获取工区全部摄像头
            if ($work_area_id > 0 && $user_type != 1) {
                $device_serial = BusinessService::areaDeviceList($work_area_id);
                $where[] = ['a.device_serial', 'in', $device_serial];
            }
            //获取站点全部摄像头
            if ($work_area_stand_id > 0) {
                $device_serial = BusinessService::siteDeviceList($work_area_stand_id);
                $where[] = ['a.device_serial', 'in', $device_serial];
            }
            $data = (new HkConsumerMsgWeek())
                ->alias('a')
                ->where($where)
                ->where('a.image_url', 'not null')
                ->where("a.image_url <> ''")
                ->field([
                    'a.id', 'a.msg_type', 'a.device_serial', 'a.channel_no', 'a.date_time', 'a.image_url', 'a.server_img_url', 'a.msg_name event_name',
                ])
                ->order("a.date_time DESC")
                ->limit(20)
                ->select()
                ->toArray();
            $ip = $this->request->ip();
            //当前时间戳
            $time = time();
            foreach ($data as $key => $val) {
                //通过消息获取摄像头表信息
                $hk_device_serial = HkDeviceSerial::where(['device_serial' => $val['device_serial'], 'channel_no' => $val['channel_no']])->cache(120)->field('id,name')->find();
                $data[$key]['bname'] = $hk_device_serial->name;
                //第一张图获取语音
                if ($key == 0) {
                    //语音播报
                    $data[$key]['broadcast'] = 0;
                    //摄像头闪烁
                    $data[$key]['is_camera'] = 0;
                    //2分钟内检查是否播报
                    if ($val['date_time'] > $time - 180) {
                        //图片报警上报检测
                        $warn_voice = WarnVoice::where(['hk_consumer_msg_id' => $val['id'], 'type' => 1, 'user_id' => $work_area_user_id, 'user_ip' => $ip])->value('id');
                        if (empty($warn_voice)) {
                            $voice_file = WorkAreaStandVoice::where(['hk_device_serial_id' => $hk_device_serial->id, 'event_type' => $val['event_name']])
                                ->order("id DESC")
                                ->cache(60)
                                ->value('file');
                            $data[$key]['broadcast'] = 1;
                            $data[$key]['voice_file'] = get_file_url($voice_file);
                        }
                        //摄像头闪烁当前抓拍是2分钟以内的消息就爆红
                        $data[$key]['is_camera'] = 1;
                    }
                }
                $data[$key]['date_time'] = date('Y-m-d H:i:s', $val['date_time']);
                $data[$key]['image_url'] = get_file_url($val['image_url']);
                $data[$key]['server_img_url'] = get_file_url($val['image_url']);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $data);
    }


    /**
     * @Apidoc\Title("语音播报后上报记录")
     * @Apidoc\Url("/screen/work_area.Info/webWarnVoice")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("hk_consumer_msg_id",type="int", desc="记录id")
     * @Apidoc\Param("type",type="int", desc="1图片上报 2摄像头上报")
     * @Apidoc\Returned("data", type="object", desc="对象信息")
     */
    public function webWarnVoice()
    {
        try {
            $param = $this->request->param();
            $result = JWTAuth::auth();
            $work_area_user_id = $result['work_area_user'];
            $data = [
                'hk_consumer_msg_id|记录id' => 'require',
            ];
            Validate($data)->check($param);
            WarnVoice::create([
                'hk_consumer_msg_id' => $param['hk_consumer_msg_id'],
                'type' => $param['type'] ?? 1,
                'user_id' => $work_area_user_id,
                'user_ip' => $this->request->ip(),
            ]);
            if (!RedisQuantity::FrequencyLimit(md5(request()->controller() . request()->action() . $work_area_user_id), 3)) {
                throw new \Exception('请求频繁,稍后再试');
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '操作成功');
    }


    /**
     * @Apidoc\Title("AI识别预警类型统计分析")
     * @Apidoc\Url("/screen/work_area.Info/monthStatistics")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="站点id 默认值传0")
     * @Apidoc\Returned("data", type="object", desc="对象信息" )
     */
    public function monthStatistics()
    {
        try {
            ini_set('memory_limit', '1024M');
            set_time_limit(0);
            $work_area_id = input('post.work_area_id/d', 0);
            $where = [];
            if ($work_area_id > 0) {
                //获取全部摄像头
                $device_serial = BusinessService::areaDeviceList($work_area_id);
                $where[] = ['device_serial', 'in', $device_serial];
            }
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            //获取站点全部摄像头
            if ($work_area_stand_id > 0) {
                $device_serial = BusinessService::siteDeviceList($work_area_stand_id);
                $where[] = ['device_serial', 'in', $device_serial];
            }

            //获取当前日期
            $currentMonth = date('m-d');
            // 创建存储月份的数组
            $day = [];
            // 将今天日期添加到数组
            $day[] = ['time' => $currentMonth];
            // 生成前6天的数组
            for ($i = 1; $i <= 6; $i++) {
                // 计算几天前的日期
                $previousMonth = date('m-d', strtotime("-{$i} days"));
                // 将几天前的日期加入到数组
                $day[] = ['time' => $previousMonth];
            }
            //只获取下面数组事件
            $event_arr_id = HkEventType::$event_arr_id;
            $hk_event_type = HkEventType::where(['id' => $event_arr_id])->cache(30)->column('remarks');
            //获取每个事件前7个天的数据数组
            $data = [];
            //循环事件
            foreach ($hk_event_type as $key => $val) {
                $data[$key]['name'] = $val;
                $data[$key]['type'] = 'line';
                $data[$key]['stack'] = 'Total';
                //循环天数，获取每天数据到每个事件数组中
                foreach ($day as $v) {
                    $msg_type_count = HkConsumerMsg::where($where)
                        ->whereDay('date_time', date("Y") . '-' . $v['time'])
                        ->where('msg_name', $val)
                        ->cache(600)
                        ->count('*');
                    $data[$key]['data'][] = $msg_type_count;
                }
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', [
            'months' => $day,
            'data' => $data
        ]);
    }


    /**
     * @Apidoc\Title("获取站点列表")
     * @Apidoc\Url("/screen/work_area.Info/siteList")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="站点id 默认值传0")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("id", type="int", desc="id"),
     *    @Apidoc\Returned("name", type="string", desc="名字"),
     *    @Apidoc\Returned("addr", type="string", desc="地址"),
     *    @Apidoc\Returned("longitude", type="string", desc="经度"),
     *    @Apidoc\Returned("latitude", type="string", desc="纬度"),
     *    @Apidoc\Returned("today", type="string", desc="今日"),
     *    @Apidoc\Returned("month", type="string", desc="当月"),
     *    @Apidoc\Returned("whole", type="string", desc="累计"),
     *    @Apidoc\Returned("on_line", type="string", desc="在线"),
     *    @Apidoc\Returned("offline", type="string", desc="离线"),
     * )
     */
    public function siteList()
    {
        try {
            $work_area_id = input('post.work_area_id/d', 0);
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            $where = [];
            if ($work_area_id > 0) $where = ['work_area_id' => $work_area_id];
            if ($work_area_stand_id > 0) $where = ['id' => $work_area_stand_id];
            $list = WorkAreaStand::where($where)
                ->order("sort DESC")
                ->field('id,name,addr,longitude,latitude,work_area_id,is_use')
                ->select()
                ->toArray();

            //只获取下面数组事件
            //$event_arr = BusinessService::$event_arr;
            foreach ($list as $k => $v) {
                //报警统计
                $list[$k]['today'] = HkConsumerMsgWeek::where(['work_area_stand_id' => $v['id']])->where('image_url', 'not null')->whereDay('date_time')->count('*');
                $list[$k]['month'] = HkConsumerMsg::where(['work_area_stand_id' => $v['id']])->where('image_url', 'not null')->whereMonth('date_time')->count('*');
                $list[$k]['whole'] = HkConsumerMsg::where(['work_area_stand_id' => $v['id']])->where('image_url', 'not null')->count('*');
                //工点详情统计
                $list[$k]['on_line'] = HkDeviceSerial::where(['work_area_stand_id' => $v['id'], 'is_exist' => 1])->count('*');
                $list[$k]['offline'] = HkDeviceSerial::where(['work_area_stand_id' => $v['id'], 'is_exist' => 2])->count('*');
                //报警详细统计 warn
                $list[$k]['warn'] = HkConsumerMsg::where(['work_area_stand_id' => $v['id']])
                    ->where('image_url', 'not null')
                    ->field(['msg_type', "count('msg_type') msg_type_count", 'msg_name remarks'])
                    ->group('msg_name')
                    ->cache(30)
                    ->select()
                    ->toArray();
                //是否闪烁
                $is_camera = (new HkConsumerMsgWeek())->where(['work_area_stand_id' => $v['id']])
                    ->where('image_url', 'not null')
                    ->where("date_time >= " . (time() - 120))
                    ->order("date_time DESC")
                    ->field(['msg_name,date_time'])
                    ->find();
                $list[$k]['is_camera'] = empty($is_camera) ? 0 : 1;
                unset($is_camera);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $list);
    }


    /**
     * @Apidoc\Title("获取摄像头列表")
     * @Apidoc\Url("/screen/work_area.Info/cameraList")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="站点ID")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("id", type="int", desc="id"),
     *    @Apidoc\Returned("device_serial", type="string", desc="设备录像机编号"),
     *    @Apidoc\Returned("channel_no", type="string", desc="通道号"),
     *    @Apidoc\Returned("type", type="string", desc="1枪机 2球机"),
     *    @Apidoc\Returned("lefts", type="string", desc="左坐标"),
     *    @Apidoc\Returned("tops", type="string", desc="上坐标"),
     *    @Apidoc\Returned("is_exist", type="int", desc="1上线 2下线"),
     *    @Apidoc\Returned("warn", type="string", desc="预警记录"),
     *    @Apidoc\Returned("is_camera", type="int", desc="1闪烁 0不闪烁")
     * )
     */
    public function cameraList()
    {
        try {
            $work_area_stand_id = input('post.work_area_stand_id/s', 1);
            $list = HkDeviceSerial::where(['work_area_stand_id' => $work_area_stand_id])->select()->toArray();
            $time = time();
            foreach ($list as $key => $val) {
                //查询摄像头最后一条预警信息
                $list[$key]['warn'] = '';
                //摄像头闪烁当前抓拍是2分钟以内的消息就爆红
                $list[$key]['is_camera'] = 0;
                $HkConsumerMsg = HkConsumerMsgWeek::where(['work_area_stand_id' => $work_area_stand_id])
                    ->where(['channel_no' => $val['channel_no']])
                    ->where(['device_serial' => $val['device_serial']])
                    ->where('image_url', 'not null')
                    ->order("date_time DESC")
                    ->field(['msg_name,date_time'])
                    ->cache(60)
                    ->find();
                if (!empty($HkConsumerMsg)) {
                    $list[$key]['warn'] = $HkConsumerMsg->msg_name;
                    $list[$key]['is_camera'] = $HkConsumerMsg->date_time > $time - 120 ? 1 : 0;
                }
                $list[$key]['alarm_count'] = HkConsumerMsgWeek::where(['work_area_stand_id' => $work_area_stand_id])
                    ->where(['channel_no' => $val['channel_no']])
                    ->where(['device_serial' => $val['device_serial']])
                    ->where('image_url', 'not null')
                    ->whereDay('create_time')
                    ->count('*');
                unset($HkConsumerMsg);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $list);
    }

    /**
     * @Apidoc\Title("获取标准流预览/回放地址")
     * @Apidoc\Url("/screen/work_area.Info/getVideoUrl")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("deviceSerial",type="string", desc="设备序列号")
     * @Apidoc\Param("channelNo",type="int", desc="通道号")
     * @Apidoc\Param("protocol",type="int", desc="流播放协议，2-hls、3-rtmp、4-flv")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("id", type="int", desc="id"),
     *    @Apidoc\Returned("url", type="string", desc="流地址"),
     *     )
     */
    public function getVideoUrl()
    {
        try {
            $deviceSerial = input('post.deviceSerial/s', 'AD5513848');
            $channelNo = input('post.channelNo/d', 1);
            $protocol = input('post.protocol/d', 2);
            if ($deviceSerial != 'AD5513816') {
                $access_token = HaikangService::accessToken();
                $url = "https://api2.hik-cloud.com/v1/carrier/wing/endpoint/video/getVideoUrl?deviceSerial={$deviceSerial}&channelNo={$channelNo}&protocol={$protocol}";
                $res = httpGet($url, 'Authorization: Bearer' . $access_token['access_token']);
                $res = json_decode($res, true);
            } else {
                $url = "https://api2.hik-cloud.com/v1/carrier/wing/endpoint/video/getVideoUrl?deviceSerial=K87458457&channelNo={$channelNo}&protocol={$protocol}";
                //红牌楼特殊处理
                $res = httpGet($url, 'Authorization: Bearer03a293c3-7ab1-4ff1-88ac-eec8a67b5352');
                $res = json_decode($res, true);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $res);
    }


    /**
     * @Apidoc\Title("获取站点统计")
     * @Apidoc\Url("/screen/work_area.Info/statisticsSite")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("id", type="int", desc="id"),
     *    @Apidoc\Returned("name", type="string", desc="站点名"),
     *    @Apidoc\Returned("warn1", type="int", desc="未带安全帽数量"),
     *    @Apidoc\Returned("warn2", type="int", desc="玩手机"),
     *    @Apidoc\Returned("warn3", type="int", desc="抽烟"),
     *    @Apidoc\Returned("warn4", type="int", desc="未穿反光衣"),
     * )
     */
    public function statisticsSite()
    {
        try {
            $work_area_id = input('post.work_area_id/s', 5);
            $proj_line_id = WorkArea::where('proj_line_id', 'IN', function ($query) use ($work_area_id) {
                $query->name('proj_line')->where('id', $work_area_id)->field('id');
            })->column('id');
            //工点列表
            $work_area_stand = WorkAreaStand::where(['work_area_id' => $proj_line_id, 'is_use' => 1])
                ->field(['id', 'name'])
                ->select()
                ->toArray();
            foreach ($work_area_stand as $key => $val) {
                $work_area_stand[$key]['warn1'] = HkConsumerMsg::where(['msg_name' => '安全帽未佩戴', 'work_area_stand_id' => $val['id']])->cache(120)->count('*');
                $work_area_stand[$key]['warn2'] = HkConsumerMsg::where(['msg_name' => '打电话', 'work_area_stand_id' => $val['id']])->cache(120)->count('*');
                $work_area_stand[$key]['warn3'] = HkConsumerMsg::where(['msg_name' => '抽烟', 'work_area_stand_id' => $val['id']])->cache(120)->count('*');
                $work_area_stand[$key]['warn4'] = HkConsumerMsg::where(['msg_name' => '反光衣未穿戴', 'work_area_stand_id' => $val['id']])->cache(120)->count('*');
            }

        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $work_area_stand);
    }


    /**
     * @Apidoc\Title("获取站点当天的详细类型统计")
     * @Apidoc\Url("/screen/work_area.Info/todayMsgCorr")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="工点ID")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("name", type="string", desc="站点名"),
     *    @Apidoc\Returned("count", type="int", desc="数量")
     * )
     */
    public function todayMsgCorr()
    {
        try {
            $work_area_stand_id = input('post.work_area_stand_id/s', 10);
            $list = [
                ['name' => '高空安全带识别', 'count' => 0],
                ['name' => '临边防护', 'count' => 0],
                ['name' => '打电话', 'count' => 0],
                ['name' => '反光衣未穿戴', 'count' => 0],
                ['name' => '抽烟', 'count' => 0],
                ['name' => '安全帽未佩戴', 'count' => 0],
                ['name' => '翻越围栏', 'count' => 0],
                ['name' => '黄土裸露', 'count' => 0],
            ];
            foreach ($list as $key => $val) {
                $count = HkConsumerMsgWeek::where([
                    'work_area_stand_id' => $work_area_stand_id, 'msg_name' => $val['name']
                ])->whereDay('create_time')->count('*');
                $list[$key]['count'] = $count > 50 ? 50 : $count;
                unset($count);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '获取成功', $list);
    }

}